<?php
/**
 * @abstract: Trang Đăng tin rao vặt
 * @author: HoanVX
 * @version $Id: post.php 91 2015-05-14 13:16:33Z voxuanhoan@gmail.com $
 */

/*
 * Template Name: Post entry
 */

// session_start();
require_once (ABS_THEME_PATH .'helper/dbtransaction.php');

// If user is not login, rediect to login page
if (!is_user_logged_in()) {
	//'page/login.php'
	wp_redirect(get_the_permalink(33));
}


// If submit
$postId = ChotroiUtils::convertPostNullToBlank('postId');
$category = ChotroiUtils::convertPostNullToBlank('category');
$city = ChotroiUtils::convertPostNullToBlank('city');
$district = ChotroiUtils::convertPostNullToBlank('district');
$postTitle = ChotroiUtils::convertPostNullToBlank('postTitle');
$postContent = ChotroiUtils::convertPostNullToBlank('postContent');
$postPurpose = ChotroiUtils::convertPostNullToBlank('postPurpose');
$postEndDate = ChotroiUtils::convertPostNullToBlank('postEndDate');
$price = ChotroiUtils::convertPostNullToBlank('price');
$note = ChotroiUtils::convertPostNullToBlank('note');

// Get temporary image path if image has been uploaded by ajax:
$imgNo1 = ChotroiUtils::convertPostNullToBlank('imgNo1');
$imgNo2 = ChotroiUtils::convertPostNullToBlank('imgNo2');
$imgNo3 = ChotroiUtils::convertPostNullToBlank('imgNo3');
$imgNo4 = ChotroiUtils::convertPostNullToBlank('imgNo4');
$imgNo5 = ChotroiUtils::convertPostNullToBlank('imgNo5');

// Case update post has existed from DB
// Transmit from screen /post-manager/
if (isset($_GET['act']) &&  isset($_GET['postId']) && strcmp($_GET['act'], "edit") == 0 && !empty($_GET['postId'])) {
	$postId = $_GET['postId'];
	$postRst = get_post($postId);

	// Get information for display.
	$category = get_the_category($postId)[0]->cat_ID;
	$city = get_post_meta($postId, CT_CITY, true);
	$district = get_post_meta($postId, CT_DISTRICT, true);
	$postTitle = $postRst->post_title;
	$postContent = $postRst->post_content;
	$postPurpose = get_post_meta($postId, CT_POST_PURPOSE, true);
	$postEndDate = get_post_meta($postId, CT_POST_END_DATE, true);
	$price = get_post_meta($postId, CT_PRICE, true);
	$note = get_post_meta($postId, CT_NOTE, true);

	// Get images from chotrois.com/upload/post-images/yyyy/mm/image file name.
	// if image has been registed, Image path would never contain phase "noimage.jpg"
	$imgNo1 = ChotroiUtils::getUploadImageURI(ChotroiUtils::getAttachImage($postId)[0]);
	$imgNo2 = ChotroiUtils::getUploadImageURI(ChotroiUtils::getAttachImage($postId)[1]);
	$imgNo3 = ChotroiUtils::getUploadImageURI(ChotroiUtils::getAttachImage($postId)[2]);
	$imgNo4 = ChotroiUtils::getUploadImageURI(ChotroiUtils::getAttachImage($postId)[3]);
	$imgNo5 = ChotroiUtils::getUploadImageURI(ChotroiUtils::getAttachImage($postId)[4]);

	//TODO: Get data from database to load on screen

	// If da transmit to post-confirm.php page
} else if (isset($_SESSION['postData']) && !empty($_SESSION['postData'])) {

	// iF USER TRY TO enter this page by URL, I will forward to post-confirm.php
	if (empty($_SESSION['doBack']))
		// page/post-confirm.php page
		wp_redirect(get_the_permalink(49));

	// back to this page from post-confirm.php page
	else if (!isset($_POST['doConfirm'])) {
		$postData 		= $_SESSION['postData'];

		$category 		= $postData['category'];
		$city 			= $postData['city'];
		$district 		= $postData['district'];
		$postTitle 		= $postData['postTitle'];
		$postContent 	= $postData['postContent'];
		$postPurpose	= $postData['postPurpose'];
		$postEndDate	= $postData['postEndDate'];
		$price			= $postData['price'];
		$note			= $postData['note'];
		$imgNo1			= isset($postData['imgNo1']['url'])? $postData['imgNo1']['url'] : "";
		$imgNo2			= isset($postData['imgNo2']['url'])? $postData['imgNo2']['url'] : "";
		$imgNo3			= isset($postData['imgNo3']['url'])? $postData['imgNo3']['url'] : "";
		$imgNo4			= isset($postData['imgNo4']['url'])? $postData['imgNo4']['url'] : "";
		$imgNo5			= isset($postData['imgNo5']['url'])? $postData['imgNo5']['url'] : "";
	} else {

		// Neu submit lai (BACK VE TU PAGE CONFIRM) thi ju lai ID de update data
		$postId			= $_SESSION['postData']['postId'];
	}
}


// Validate POST value when user submit form
$postValidate = new Validation();
if (isset($_POST['doConfirm'])) {
	// Validate item
	if (empty($category))
		$postValidate->setError('category', Messages::ERROR_CATEGORY_REQUIRED);

	if (empty($city))
		$postValidate->setError('city', Messages::ERROR_CITY_REQUIRED);

	if (empty($postTitle))
		$postValidate->setError('postTitle', Messages::ERROR_POST_TITLE_REQUIRED);
	else if (strlen($postTitle) > 300)
		$postValidate->setError('postTitle', Messages::ERROR_POST_TITLE_MAXLENGTH);

	if (empty($postContent))
		$postValidate->setError('postContent', Messages::ERROR_POST_CONTENT_REQUIRED);
	else if (strlen($postContent) > 8000)
		$postValidate->setError('postContent', Messages::ERROR_POST_CONTENT_MAXLENGTH);

	if (empty($postPurpose))
		$postValidate->setError('postPurpose', Messages::ERROR_POST_PURPOSE_REQUIRED);
	else if (strlen($postPurpose) > 8000)
		$postValidate->setError('postPurpose', Messages::ERROR_POST_PURPOSE_MAXLENGTH);

	if (!empty($postEndDate)) {
// 		if ()TODO
	}

	if (empty($price))
		$postValidate->setError('price', Messages::ERROR_PRICE_REQUIRED);
	else if (strlen($price) > 40)
		$postValidate->setError('price', Messages::ERROR_PRICE_MAXLENGTH);
	else if (!is_numeric($price))
		$postValidate->setError('price', Messages::ERROR_PRICE_NUMBER);

	if (strlen($note) > 1000)
		$postValidate->setError('note', Messages::ERROR_NOTE_MAXLENGTH);

	if (!$postValidate->hasError()) {
		$transaction = new DBTransaction();
		try {
			$transaction->beginTransaction();

			$postArr = array(
					'ID'			 => $postId,
					'post_content'   => esc_html($postContent),
					'post_name'      =>  '', //[ <string> ] // The name (slug) for your post
					'post_title'     => esc_html($postTitle),
					'post_status'    => 'draft', // [ 'draft' | 'publish' | 'pending'| 'future' | 'private' | custom registered status ] // Default 'draft'.
					'post_type'      => 'post', //[ 'post' | 'page' | 'link' | 'nav_menu_item' | custom post type ] // Default 'post'.
					'post_author'    => get_current_user_id(),  // The user ID number of the author. Default is the current user ID.
					'post_excerpt'   => substr(esc_html($postContent),0, 200),  // For all your post excerpt needs.
					'comment_status' => 'open', //[ 'closed' | 'open' ] // Default is the option 'default_comment_status', or 'closed'.
					'post_category'  => array($category),
					'tags_input'     => '', //[ '<tag>, <tag>, ...' | array ] // Default empty.
					'tax_input'      => '' // [ array( <taxonomy> => <array | string> ) ] // For custom taxonomies. Default empty.
			);

			$postId = wp_insert_post($postArr);
			if ($postId != 0) {
				$transaction->commit();

				// existed postId mean user has submited form (doConfirm) at least 1 times
				if (isset($_SESSION['postData']['postId'])) {
 					$postData = ChotroiUtils::parseAndMerge($_POST, $_SESSION['postData']);
 					$_SESSION['postData'] = $postData;

				// First times user submit form (doConfirm)
				} else {
					$defaultSession = array(
											'postId'		=> $postId,
											'category'		=> $category,
											'city'			=> $city,
											'district'		=> $district,
											'postTitle'		=> $postTitle,
											'postContent'	=> $postContent,
											'postPurpose'	=> $postPurpose,
											'postEndDate'	=> $postEndDate,
											'price'			=> $price,
											'note'			=> $note
										);

					// Existed $_SESSION['postData'] because user has been uploaded images
					$_SESSION['postData'] = wp_parse_args($_SESSION['postData'], $defaultSession);
				}

				// remove command doBack from confirm screen
				unset($_SESSION['doBack']);

				// rediect to page/post-confirm.php page
				wp_redirect(get_the_permalink(49));
			} else {
				session_unset();
				session_destroy();
				$postValidate->setMessage("insWarning", Messages::WARNING_POST_ENTRY);
			}
		} catch (Exception $e) {
			$transaction->rollBack();
		}
	} else {

	}
}
// End if Submit
add_style('css/page/postEntry.css');
add_script("js/jquery.validate.js");
add_script('js/page/postEntry.js');
get_header();


?>
<!-- header-section-ends -->
<!-- content-section-starts -->
<div class="content">
	<div class="container">
		<div class="col-sm-8 col-md-8" id="postLeft">
		  	<h2>Đăng tin rao vặt</h2>
		  	<?php if ($postValidate->hasMessage())
		  			echo TagUtils::genMessagePanel($postValidate->getMessages());
		  	?>
		  	<form role="form" id="postForm" method="POST" enctype="multipart/form-data">
		  		<div class="row">
		  			<div class="form-group col-lg-4 col-sm-12 col-md-12">
				      	<label for="category" class="label label-info">Chuyên mục đăng</label>
				      	<?php
			      			echo TagUtils::genCategoryPulldown(array('firstOption' => 'Chọn danh mục để đăng tin', 'defaultSelected'=>$category));
				      		echo $postValidate->getError('category');
				      	?>
			    	</div>
			    	<div class="form-group col-lg-4 col-sm-12 col-md-12">
				      	<label for="city" class="label label-info">Khu vực đăng (Thành phố):</label>
		      			<?php echo CityEnum::getCityPulldown(array('defaultSelected'=>$city));?>
				      	<?php echo $postValidate->getError('city');?>
			    	</div>
			    	<div class="form-group col-lg-4 col-sm-12 col-md-12">
				      	<label for="district" class="label label-info">Khu vực đăng (Huyện):</label>
				      	<?php echo CityEnum::getDistrictPulldown();
				      		TagUtils::inputTag(array('id'=>'hdnDistrict', 'value'=>$district));
				      	?>
			    	</div>
			    	<?php echo $postValidate->getError('district');?>
		  		</div>
		  		<div class="row">
		  			<div class="form-group col-lg-12 col-md-12 col-sm-12" >
				      	<label for="title" class="label label-info">Tiêu đề:</label>
				     	<input type="text" name="postTitle" class="form-control" id="title" placeholder="Hãy nhập tiêu đề cho nội dung tin đăng của bạn" value="<?php echo $postTitle?>">
				     	<?php echo $postValidate->getError('postTitle');?>
			    	</div>
		  		</div>
		  		<div class="row">
		  			<div class="form-group col-lg-12 col-md-12 col-sm-12">
				      	<label for="content" class="label label-info">Nội dung của tin:</label>
				      	<textarea class="form-control" name="postContent" rows="6" cols="" id="content"
				      			placeholder="Nhập vào nội dung tin của bạn muốn đăng"><?php echo trim($postContent);?></textarea>
			    		<?php echo $postValidate->getError('postContent');?>
			    	</div>
			  	</div>
			  	<div class="row">
		  			<div class="form-group col-lg-6 col-md-12 col-sm-12">
				      	<label for="purpose" class="label label-info">Bạn đăng tin để:</label>
				      	<div class="btn-group" data-toggle="buttons">
					      	<label class="btn btn-success <?php if ($postPurpose==1) echo 'active';?>">
					    		<input type="radio" name="postPurpose" id="purpose" autocomplete="off" value="1" <?php if ($postPurpose == 1) echo 'checked="checked"'; ?> /> Cần bán
						  	</label>
					      	<label class="btn btn-success <?php if ($postPurpose==2) echo 'active';?>">
					    		<input type="radio" name="postPurpose" id="purpose" autocomplete="off" value="2" <?php if ($postPurpose == 2) echo 'checked="checked"'; ?> > Cần mua
						  	</label>
						</div>
						<div id="abcd"></div>
						<?php echo $postValidate->getError('postPurpose');?>
			    	</div>
			    	<div class="col-lg-6 col-md-12 col-sm-12">
			    		<label for="postEndDate" class="label label-info">Ngày hết hạn của tin:</label>
				      	<input class="form-control" name="postEndDate" id="postEndDate" placeholder="Nhập ngày hết hạn của tin." maxlength="10">
			    		<?php echo $postValidate->getError('postEndDate');?>
			    	</div>
			  	</div>
			  	<div class="row">
			    	<div class="form-group col-lg-12 col-md-12 col-sm-12">
				      	<label for="image" class="label label-info" >Hãy upload hình ảnh để tăng thêm sự tin cậy của người mua</label>
				      	<div class="row">
				      		<div class=" col-md-2 col-sm-2 img-area">
					      		<?php echo TagUtils::img(array('id'=>'img1', 'alt'=>'Hình thứ 1', 'src'=> $imgNo1, 'height'=>123, 'width'=>123));?>
					      		<label for="upImg1" class="btn btn-primary imgChoose">Upload hinh 1</label>
					      		<input type="file"  class="form-control" id="upImg1" name="imgFile1" onchange="uploadFile(this);"/>
					      	</div>
					      	<div class=" col-md-2 col-sm-2 img-area">
					      		<?php echo TagUtils::img(array('id'=>'img2', 'alt'=>'Hình thứ 2', 'src'=> $imgNo2, 'height'=>123, 'width'=>123));?>
					      		<label for="upImg2" class="btn btn-primary imgChoose">Upload hinh 2</label>
					      		<input type="file"  class="form-control" id="upImg2" name="imgFile2" onchange="uploadFile(this);"/>
					      	</div>
					      	<div class="col-md-2 col-sm-2 img-area">
					      		<?php echo TagUtils::img(array('id'=>'img3', 'alt'=>'Hình thứ 3', 'src'=> $imgNo3, 'height'=>123, 'width'=>123));?>
					      		<label for="upImg3" class="btn btn-primary imgChoose">Upload hinh 3</label>
					      		<input type="file"  class="form-control" id="upImg3"  name="imgFile3" onchange="uploadFile(this);"/>
					      	</div>
					      	<div class="col-md-2 col-sm-2 img-area">

					      		<?php echo TagUtils::img(array('id'=>'img4', 'alt'=>'Hình thứ 4', 'src'=> $imgNo4, 'height'=>123, 'width'=>123));?>
					      		<label for="upImg4" class="btn btn-primary imgChoose">Upload hinh 4</label>
					      		<input type="file"  class="form-control" id="upImg4" name="imgFile4" onchange="uploadFile(this);" />
					      	</div>
					      	<div class="col-md-2 col-sm-2 img-area">
					      		<?php echo TagUtils::img(array('id'=>'img5', 'alt'=>'Hình thứ 5', 'src'=> $imgNo5, 'height'=>123, 'width'=>123));?>
					      		<label for="upImg5" class="btn btn-primary imgChoose">Upload hinh 5</label>
					      		<input type="file"  class="form-control" id="upImg5" name="imgFile5" onchange="uploadFile(this);" />
					      	</div>
				      	</div>
				      	<div class="row">
				      		<p class="col-lg-12 col-md-12 img-note"><span>&nbsp;<strong class="error">(*)</strong>&nbsp;</span><i>Dung lượng tối da cho mỗi hình là 1MB</i></p>
				      	</div>
			    	</div>
		    	</div>
		    	<div class="row">
		  			<div class="form-group col-lg-12 col-md-12">
				      	<label for="price" class="label label-info">Giá của sản phẩm:</label>
				      	<input type="text" name="price" class="form-control" placeholder="Nhập vào giá của sản phầm mà bán muốn bán hoặc mua" value="<?php echo $price;?>"/>
				      	<?php echo $postValidate->getError('price');?>
			    	</div>
			  	</div>
			  	<div class="row">
		  			<div class="form-group col-lg-12 col-md-12">
				      	<label for="note" class="label label-info">Ghi chú:</label>
				      	<textarea class="form-control" rows="5" cols="" name="note" id="note" placeholder="Cách thanh toán, quy trình vận chuyển, giao và nhận,... " ><?php echo trim($note);?></textarea>
			    		<?php echo $postValidate->getError('note');?>
			    	</div>
			  	</div>
		    	<div class="row">
		    		<div class="form-group col-lg-12 col-md-12">
		    			<button type="submit" class="btn btn-warning" name="doConfirm">Tiếp tục</button>
		    		</div>
		    	</div>

		  	</form>
		</div>
		<div class="col-sm-4 col-md-4" id="postRight">
			<h2>Lưu ý</h2>
		</div>
	</div>

	<!-- Temporary form -->
	<form action="" method="POST" id="tmpForm" style="display: none;" enctype="multipart/form-data">
		<input type="hidden" id="hdPosition" name="imgPosition">
    	<input type="hidden" name="action" value="uploadImg" id="ajaxAction"/>
	</form>

<!-- Contact's information -->
<?php get_footer("contact");?>
<!-- END Contact's information -->
</div>
<!-- content-section-ends -->
<!-- footer-section-starts -->
<?php get_footer();?>